package com.dandelion.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dandelion.business.entity.SysRoleMenu;
import com.dandelion.business.entity.vo.role.req.BindMenuReqVO;
import com.dandelion.business.mapper.SysRoleMenuMapper;
import com.dandelion.business.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dandelion.framework.common.R;
import com.dandelion.framework.enums.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 宋发准
 * @since 2021-12-26
 */
@Service
@Slf4j
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {


    /**
     * 绑定菜单
     *
     * @param req 要求事情
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    @Transactional
    public R<Boolean> bindMenu(BindMenuReqVO req) {
        Long rid = req.getRid();
        //清除旧数据
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, rid);
        remove(wrapper);

        //保存新数据
        Set<Long> mids = req.getMids();
        ArrayList<SysRoleMenu> menus = new ArrayList<>();
        for (Long mid : mids) {
            SysRoleMenu menu = new SysRoleMenu();
            menu.setRoleId(rid);
            menu.setMenuId(mid);
            menus.add(menu);
        }
        boolean batch = false;
        try {
            batch = saveBatch(menus);
            if (batch) {
                return R.ok().data(true);
            }
        } catch (Exception e) {
            log.warn("角色绑定资源异常:{}", e.getMessage());
        }
        return R.fail(CodeEnum.ROLE_BIND_MENU_ERROR).data(batch);
    }
}
